package com.shaoshaohuo.app.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TabHost;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.OrderListAdapter;
import com.shaoshaohuo.app.adapter.OrderShipperListAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Order;
import com.shaoshaohuo.app.entity.OrderListEntity;
import com.shaoshaohuo.app.framework.IViewFramework;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.OrderDetailActivity;
import com.shaoshaohuo.app.ui.shipper.OrderDetailShipperActivity;
import com.shaoshaohuo.app.utils.ViewHelper;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 物流：我的订单
 * Created by YinSF on 16/1/8.
 */
public class CarOrderFragment extends BaseFragment implements IViewFramework, View.OnClickListener,
        TabHost.OnTabChangeListener, XListView.IXListViewListener, AdapterView.OnItemClickListener {

    private static final int STATUS_IN_PROGRESS = 2;
    private static final int STATUS_OVERDONE = 3;
    private static final int STATUS_INVALID = 5;

    private String mArgument;
    public static final String ARGUMENT = "argument";
    /**
     * 当前fragment，带返回标识
     */
    public static final String ARGUMENT_VALUE_WITH_BACK = "ARGUMENT_VALUE_WITH_BACK";
    private static final String TAB_ONE = "TAB_ONE";
    private static final String TAB_TWO = "TAB_TWO";
    private static final String TAB_THREE = "TAB_THREE";
    private View view;
    private TabHost tabHost;
    private TextView textHuoZhu;
    private TextView textCheZhu;
    private XListView mOrderListInProgressview;
    private XListView mOrderListOverDoneview;
    private XListView mOrderListInvalidview;

    private OrderShipperListAdapter<Order> mAdapterCarHuoZhu;
    private OrderListAdapter<Order> mAdapterCarCheZhu;

    private List<Order> mDataList = new ArrayList<Order>();
    private int size = 10;
    private String action = ListViewAction.NEW;
    private String cursor = "0";
    private int searchstatus = STATUS_IN_PROGRESS;

    public CarOrderFragment() {
    }

    public static CarOrderFragment newInstance(String argument, Context mContext) {
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT, argument);
        CarOrderFragment contentFragment = new CarOrderFragment();
        contentFragment.setArguments(bundle);
        return contentFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null)
            mArgument = bundle.getString(ARGUMENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_my_orders, container, false);
        init();
        return view;
    }

    @Override
    public void init() {
        initView();
        initData();
        initListener();
    }

    @Override
    public void initView() {
        TopbarView topBar = (TopbarView) view.findViewById(R.id.topbar);
        topBar.setCenterText("我的订单");

        if (ARGUMENT_VALUE_WITH_BACK.equals(mArgument)) {
            topBar.setLeftClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().popBackStack();
                }
            });
        }

        textCheZhu = (TextView) view.findViewById(R.id.textview_chezhu);
        textHuoZhu = (TextView) view.findViewById(R.id.textview_huozhu);

        textCheZhu.setSelected(true);

        tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
        tabHost.setup();
        TabHost.TabSpec tab1 = tabHost.newTabSpec(TAB_ONE);
        tab1.setIndicator("进行中");
        tab1.setContent(R.id.linearLayout_inProgress);
        tabHost.addTab(tab1);
        TabHost.TabSpec tab2 = tabHost.newTabSpec(TAB_TWO);
        tab2.setIndicator("已完成");
        tab2.setContent(R.id.linearLayout_overDone);
        tabHost.addTab(tab2);
        TabHost.TabSpec tab3 = tabHost.newTabSpec(TAB_THREE);
        tab3.setIndicator("已失效");
        tab3.setContent(R.id.linearLayout_invalid);
        tabHost.addTab(tab3);
        ViewHelper.setTabHostStyle(tabHost.getTabWidget(), getContext(), 0);
        mOrderListInProgressview = (XListView) view.findViewById(R.id.listview_list_inProgress);
        mOrderListOverDoneview = (XListView) view.findViewById(R.id.listview_list_overDone);
        mOrderListInvalidview = (XListView) view.findViewById(R.id.listview_list_invalid);
    }

    @Override
    public void initData() {
        if (textCheZhu.isSelected()) {
            getOrderListCheZhu(true);
        } else if (textHuoZhu.isSelected()) {
            getOrderListHuoZhu(true);
        }
    }

    private void getOrderListHuoZhu(boolean isLoading) {
        if(isLoading){
            startLoadingDialog();
        }
        RequestService.getInstance().getCargoOrderShipperList(getActivity(), size+"", cursor+"", action, searchstatus+"", OrderListEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    OrderListEntity entity = (OrderListEntity) resultData;
                    List<Order> list = entity.getData().getList();
                    mDataList.addAll(list);

                    if ((mDataList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
                        String tabId = tabHost.getCurrentTabTag();
                        if (TAB_ONE.equals(tabId)) {
                            mOrderListInProgressview.endLoadingMore("没有更多了");
                        } else if (TAB_TWO.equals(tabId)) {
                            mOrderListOverDoneview.endLoadingMore("没有更多了");
                        } else if (TAB_THREE.equals(tabId)) {
                            mOrderListInvalidview.endLoadingMore("没有更多了");
                        }
                    }
                    setAdapter(mDataList);

                }else{
                    showToast(resultData.getMsg());
                }
                onLoad();
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
                onLoad();
            }
        });
    }


    private void getOrderListCheZhu(boolean isLoading) {
        if(isLoading){
            startLoadingDialog();
        }
        RequestService.getInstance().getCargoOrderCarList(getContext(), size + "", cursor + "", action, searchstatus + "", OrderListEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    OrderListEntity entity = (OrderListEntity) resultData;
                    List<Order> list = entity.getData().getList();
                    mDataList.addAll(list);

                    if ((mDataList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
                        String tabId = tabHost.getCurrentTabTag();
                        if (TAB_ONE.equals(tabId)) {
                            mOrderListInProgressview.endLoadingMore("没有更多了");
                        } else if (TAB_TWO.equals(tabId)) {
                            mOrderListOverDoneview.endLoadingMore("没有更多了");
                        } else if (TAB_THREE.equals(tabId)) {
                            mOrderListInvalidview.endLoadingMore("没有更多了");
                        }
                    }
                    setAdapter(mDataList);

                } else {
                    showToast(resultData.getMsg());
                }
                onLoad();
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
                onLoad();
            }

        });
    }

    private void onLoad() {
        String tabId = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(tabId)) {
            onLoad(mOrderListInProgressview);
        } else if (TAB_TWO.equals(tabId)) {
            onLoad(mOrderListOverDoneview);
        } else if (TAB_THREE.equals(tabId)) {
            onLoad(mOrderListInvalidview);
        }

    }

    private void onLoad(XListView mOrderListview) {
        mOrderListview.stopRefresh();
        mOrderListview.stopLoadMore();
    }

    @Override
    public void initListener() {
        textCheZhu.setOnClickListener(this);
        textHuoZhu.setOnClickListener(this);
        tabHost.setOnTabChangedListener(this);
        setListView(mOrderListInProgressview);
        setListView(mOrderListOverDoneview);
        setListView(mOrderListInvalidview);
    }

    private void setListView(XListView listView) {
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setOnItemClickListener(this);
    }

    protected void setAdapter(List<Order> mDataList2) {
        if (textHuoZhu.isSelected()) {
            String tabId = tabHost.getCurrentTabTag();
            if (TAB_ONE.equals(tabId)) {
                freshListAdapter(mAdapterCarHuoZhu, mOrderListInProgressview, mDataList2);
            } else if (TAB_TWO.equals(tabId)) {
                freshListAdapter(mAdapterCarHuoZhu, mOrderListOverDoneview, mDataList2);
            } else if (TAB_THREE.equals(tabId)) {
                freshListAdapter(mAdapterCarHuoZhu, mOrderListInvalidview, mDataList2);
            }
        } else if (textCheZhu.isSelected()) {
            String tabId = tabHost.getCurrentTabTag();
            if (TAB_ONE.equals(tabId)) {
                freshListAdapter(mAdapterCarCheZhu, mOrderListInProgressview, mDataList2);
            } else if (TAB_TWO.equals(tabId)) {
                freshListAdapter(mAdapterCarCheZhu, mOrderListOverDoneview, mDataList2);
            } else if (TAB_THREE.equals(tabId)) {
                freshListAdapter(mAdapterCarCheZhu, mOrderListInvalidview, mDataList2);
            }
        }

    }

    /**
     * 车主列表
     * @param mAdapter
     * @param mOrderListview
     * @param mDataList2
     */
    private void freshListAdapter(OrderShipperListAdapter mAdapter, XListView mOrderListview, List<Order> mDataList2) {
        if(mAdapter == null){
            mAdapter = new OrderShipperListAdapter<Order>(getActivity(), mDataList2, false);
            mOrderListview.setAdapter(mAdapter);
        }else{
            mAdapter.setData(mDataList2);
        }
    }

    /**
     * 货主列表
     * @param mAdapter
     * @param mOrderListview
     * @param mDataList2
     */
    private void freshListAdapter(OrderListAdapter mAdapter, XListView mOrderListview, List<Order> mDataList2) {
        if(mAdapterCarHuoZhu == null){
            mAdapter = new OrderListAdapter<Order>(getActivity(), mDataList2, false);
            mOrderListview.setAdapter(mAdapter);
        }else{
            mAdapter.setData(mDataList2);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_huozhu:
                textCheZhu.setSelected(false);
                textHuoZhu.setSelected(true);
                onRefresh();
                break;
            case R.id.textview_chezhu:
                textCheZhu.setSelected(true);
                textHuoZhu.setSelected(false);
                onRefresh();
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        ViewHelper.setTabHostStyle(tabHost.getTabWidget(), getContext(), tabHost.getCurrentTab());
        if (TAB_ONE.equals(tabId)) {
            searchstatus = STATUS_IN_PROGRESS;
        } else if (TAB_TWO.equals(tabId)) {
            searchstatus = STATUS_OVERDONE;
        } else if (TAB_THREE.equals(tabId)) {
            searchstatus = STATUS_INVALID;
        }
        onRefresh();
    }

    @Override
    public void onRefresh() {
        cursor = "0";
        mDataList.clear();
        action = ListViewAction.NEW;
        String tabId = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(tabId)) {
            mOrderListInProgressview.setPullLoadEnable(true);
        } else if (TAB_TWO.equals(tabId)) {
            mOrderListOverDoneview.setPullLoadEnable(true);
        } else if (TAB_THREE.equals(tabId)) {
            mOrderListInvalidview.setPullLoadEnable(true);
        }
        initData();
    }

    @Override
    public void onLoadMore() {
        if(mDataList.size()>0){
            cursor = mDataList.get(mDataList.size()-1).getCursor();
        }else {
            cursor = "";
        }
        action = ListViewAction.HISTORY;
        initData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Order order = (Order) parent.getItemAtPosition(position);
        Class targetClass = null;
        if (textHuoZhu.isSelected()) {
            targetClass = OrderDetailShipperActivity.class;
        } else if (textCheZhu.isSelected()) {
            targetClass = OrderDetailActivity.class;
        }
        Intent intent = new Intent(getActivity(),targetClass);
        intent.putExtra(ExtraName.orderid, order.getOrderid());
        startActivity(intent);
    }
}
